package com.iakuil.app.common.restful.convert;

import com.iakuil.app.common.core.DictEnum;
import com.iakuil.app.common.core.util.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

/**
 * 字典枚举转换工厂
 *
 * @author Kai
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class DictEnumConvertFactory implements ConverterFactory<String, DictEnum<?>> {
    @Override
    public <T extends DictEnum<?>> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private static class StringToEnum<T extends DictEnum> implements Converter<String, T> {
        private Class<T> targerType;

        public StringToEnum(Class<T> targerType) {
            this.targerType = targerType;
        }

        @Override
        public T convert(String source) {
            if (StringUtils.isBlank(source)) {
                return null;
            }
            return (T) getEnumByValue(this.targerType, source);
        }
    }

    public static <T extends DictEnum<?>> Object getEnumByValue(Class<T> targetType, String source) {
        for (T enumObj : targetType.getEnumConstants()) {
            if (source.equals(String.valueOf(enumObj.getValue()))) {
                return enumObj;
            }
        }
        return null;
    }
}
